package com.intellagric.service.product;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.intellagric.common.bean.LayuiDataGridResult;
import com.intellagric.common.bean.ResponseMessage;
import com.intellagric.common.utils.ExcelUtil;
import com.intellagric.common.utils.UUIDUtils;
import com.intellagric.dao.product.ProductDao;
import com.intellagric.interfaces.product.ProductService;
import com.intellagric.mapper.ProductCategoryMapper;
import com.intellagric.mapper.ProductMapper;
import com.intellagric.mapper.ProductUsedMapper;
import com.intellagric.mapper.StorageMapper;
import com.intellagric.pojo.*;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper mapper;

    @Autowired
    private ProductDao dao;

    @Autowired
    private ProductCategoryMapper productCategoryMapper;

    @Autowired
    private ProductUsedMapper usedMapper;

    @Autowired
    private StorageMapper storageMapper;

    //返回msg格式
    public ResponseMessage selectProductById(String id) {
        ResponseMessage msg=new ResponseMessage();
        msg.add("productBean",mapper.selectByPrimaryKey(id));
        return msg;
    }
    //返回bean格式
    public Product queryProductById(String id) {
        return mapper.selectByPrimaryKey(id);
    }

    public ResponseMessage insertProduct(Product Product) {
        int i=mapper.insertSelective(Product);
        if (i!=0)
            return ResponseMessage.success();
        return ResponseMessage.fail();
    }

    public ResponseMessage deleteProduct(String id) {
        int i=mapper.deleteByPrimaryKey(id);
        if (i!=0) {
            ProductUsedExample example=new ProductUsedExample();
            example.createCriteria().andProduceIdEqualTo(id);
            usedMapper.deleteByExample(example);
            return ResponseMessage.success();
        }

        return ResponseMessage.fail();
    }

    public ResponseMessage editProduct(Product Product) {
        ProductExample example=new ProductExample();
        example.createCriteria().andProduceIdEqualTo(Product.getProduceId());
        int i =mapper.updateByExampleSelective(Product,example);
        if (i!=0)
            return ResponseMessage.success();
        return ResponseMessage.fail();
    }

    public LayuiDataGridResult getList(int page, int limit) {
        PageHelper.startPage(page,limit);
        ProductExample example=new ProductExample();
        example.createCriteria().andProduceIdIsNotNull();
        List<Product> list=mapper.selectByExample(example);
//        List<Product> list=dao.selectList();
        PageInfo info=new PageInfo(list);
        return LayuiDataGridResult.success().add(list,info.getTotal());
    }

    public LayuiDataGridResult getListByCategoryId(int page, int limit, String categoryId) {
        PageHelper.startPage(page,limit);
        ProductExample example=new ProductExample();
        example.createCriteria().andCategoryIdEqualTo(categoryId);
        List<Product> list=mapper.selectByExample(example);
//        List<Product> list=dao.selectListByCategory(categoryId);
        PageInfo info=new PageInfo(list);
        return LayuiDataGridResult.success().add(list,info.getTotal());
    }

    public LayuiDataGridResult batchDeleteProduct(String[] ids) {
        int i=dao.batchDeleteByPrimaryKey(ids);
        if (i!=0) {
            for (String id:ids){
                ProductUsedExample example=new ProductUsedExample();
                example.createCriteria().andProduceIdEqualTo(id);
                usedMapper.deleteByExample(example);
            }
            LayuiDataGridResult result = new LayuiDataGridResult();
            result.setCode(200);
            return result;
        }
        return LayuiDataGridResult.fail();
    }

    public LayuiDataGridResult getProductByKeyword(int page, int limit, String keyword) {
        PageHelper.startPage(page,limit);
        ProductExample example=new ProductExample();

        example.createCriteria().andProduceNameLike("%"+keyword+"%");
        List<Product> list=mapper.selectByExample(example);
        PageInfo info=new PageInfo(list);
        return LayuiDataGridResult.success().add(list,info.getTotal());
    }

    @Override
    public List<Map<String, String>> getPropCount() {
        List<Map<String, String>> res=new ArrayList<>();
        ProductCategoryExample categoryExample=new ProductCategoryExample();
        categoryExample.createCriteria().andParentIdEqualTo("0");
        List<ProductCategory> categoryList=productCategoryMapper.selectByExample(categoryExample);
        for (ProductCategory category:categoryList){
            int count=0;
            count=getPropCount(category.getId());
            Map<String,String> map=new HashMap<>();
            map.put("name",category.getName());
            map.put("value",String.valueOf(count));
            res.add(map);
        }
        return res;
    }

    /**
     * 递归查询该类下物品的数量
     * @param categoryId
     * @return
     */
    private int getPropCount(String categoryId){
        int result=0;
        ProductCategoryExample categoryExample=new ProductCategoryExample();
        categoryExample.createCriteria().andParentIdEqualTo(categoryId);
        ProductExample example=new ProductExample();
        example.createCriteria().andCategoryIdEqualTo(categoryId);
        result+=mapper.selectByExample(example).size();
        for(ProductCategory category:productCategoryMapper.selectByExample(categoryExample)){
            result+=getPropCount(category.getId());
        }
        return result;
    }

    @Override
    public LayuiDataGridResult addConsumableExcelData(MultipartFile uploadFile) {
        ProductCategoryExample categoryExample=new ProductCategoryExample();
        categoryExample.createCriteria().andIdIsNotNull();
        List<ProductCategory> categoryList=productCategoryMapper.selectByExample(categoryExample);
        StorageExample storageExample=new StorageExample();
        storageExample.createCriteria().andStorageIdIsNotNull();
        List<Storage> storageList=storageMapper.selectByExample(storageExample);
        List<String> productList=new ArrayList<>();
        List<String> productIds=new ArrayList<>();
        LayuiDataGridResult result=new LayuiDataGridResult();

        try {
            /*POIFSFileSystem fileSystem=new POIFSFileSystem(uploadFile.getInputStream());
            HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);*/
            Boolean first=true;
            Workbook workbook=WorkbookFactory.create(uploadFile.getInputStream());
            Sheet sheet=workbook.getSheetAt(0);//第一页
            for (Row row:sheet) {
                if (first) {
                    first = false;
                    continue;
                }
                StringBuilder product=new StringBuilder();
                Boolean available = false;

                for (int i=0,j=row.getLastCellNum();i<j;i++){
                    if(i==0){//分类名称，如果分类名称并不是已经存在的，则直接退出
                        if(row.getCell(i)==null||row.getCell(i).toString().equals(""))
                            break;
                        String categoryName=row.getCell(0).toString();
                        for (ProductCategory category:categoryList){
                            if (category.getName().equals(categoryName)){
                                available=true;
                                String id=UUIDUtils.getID();   //新存入产品的随机id
                                product.append(id);
                                productIds.add(id);
                                product.append("!"+category.getId());
                                break;
                            }
                        }
                        continue;
                    }
                    if (!available){
                        break; //如果分类名称并不是已经存在的，则直接退出
                    }
                    if (CellType.NUMERIC.compareTo(row.getCell(i).getCellType())==0) {
                        if (HSSFDateUtil.isCellDateFormatted(row.getCell(i))) {
                            System.out.println(row.getCell(i).getDateCellValue().toString());
                            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy/MM/dd");
                            product.append("!"+simpleDateFormat.format(row.getCell(i).getDateCellValue()));
                            continue;
                        }
                    }
                    if (i==row.getLastCellNum()-1){
                        if(row.getCell(i)==null||row.getCell(i).toString().equals(""))
                        {
                            product.append("!");
                            break;
                        }
                        String storageName=row.getCell(i).toString();
                        for (Storage storage:storageList){
                            if (storage.getName().equals(storageName)){
                                product.append("!"+storage.getStorageId());
                                break;
                            }
                        }
                    }else{
                        product.append("!"+row.getCell(i));
                    }
                }
                if(available) {
                    productList.add(product.toString());
                }
            }
            int i=dao.batchInsert(productList);
            if (i==productList.size()){
                result.setCode(0);
                result.setCount(i);
                result.setMsg("新增"+i+"条数据");
                result.setData(productIds);
                return result;
            }else
                return LayuiDataGridResult.fail();
        } catch (IOException e) {
            e.printStackTrace();
            return LayuiDataGridResult.fail();
        }

    }

    public void export(HttpServletRequest request, HttpServletResponse response) {


        //获取数据
        List<Product> list = dao.selectList();

        //excel标题
        String[] title = {"编号","价格","用户id"};

        //excel文件名
        String fileName = "测试表.xls";


        //sheet名
        String sheetName = "测试表";

        String[][] content=new String[list.size()][title.length];
        for (int i = 0; i < list.size(); i++) {
            content[i][0] = list.get(i).getProduceId().toString();
            content[i][1] = list.get(i).getProduceName().toString();
            content[i][2] = list.get(i).getPrice().toString();
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
            ExcelUtil.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }










}
